package cn.sangyy.gift.service.impl;

import cn.sangyy.gift.common.util.code.CodeEnum;
import cn.sangyy.gift.domain.Spu;
import cn.sangyy.gift.domain.SpuOnsaleDetail;
import cn.sangyy.gift.exception.GiftAssert;
import cn.sangyy.gift.mapper.SpuMapper;
import cn.sangyy.gift.mapper.SpuOnsaleDetailMapper;
import cn.sangyy.gift.service.ISpuService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * spu表 服务实现类
 * </p>
 *
 * @author sangyangyang
 * @since 2023-04-04
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements ISpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuOnsaleDetailMapper onSaleDetailMapper;

    //批量上架
    @Override
    public void onSale(List<Long> ids) {
        //数据校验
        GiftAssert.assertListNotNull(ids,CodeEnum.LIST_ISNULL);
        //1、判断礼物是否审核通过
        int result = spuMapper.getByIds(ids);
        if(result != ids.size()){
            GiftAssert.assertObjectIsTrue(CodeEnum.PARAM_ERROR);
        }
        //2、修改为上架状态
        spuMapper.updateStateOnSale(ids);
        //3、添加上架详情信息到数据库，便于canal同步数据
        for (Long id : ids) {
            Spu spu = selectById(id);
            SpuOnsaleDetail onSaleDetail = new SpuOnsaleDetail();
            onSaleDetail.setSpuId(spu.getId());
            onSaleDetail.setName(spu.getGoodsName());
            onSaleDetail.setTenantId(spu.getTenantId());
            onSaleDetail.setMaxPrice(spu.getHighPrice());
            onSaleDetail.setMinPrice(spu.getLowPrice());
            onSaleDetailMapper.insert(onSaleDetail);
        }
        //4、@TODO 添加上架操作日志到数据库

    }

    @Override
    public void offSale(List<Long> ids) {
        //数据校验
        GiftAssert.assertListNotNull(ids,CodeEnum.LIST_ISNULL);
        //1、判断礼物是否是上架状态
        int result = spuMapper.getByIdsOnSale(ids);
        if(result != ids.size()){
            GiftAssert.assertObjectIsTrue(CodeEnum.PARAM_ERROR);
        }
        //2、修改为下架状态
        spuMapper.updateStateOffSale(ids);
        //3、删除上架详情信息，便于canal同步数据
        onSaleDetailMapper.deleteBySupIds(ids);
        //4、@TODO 添加下架操作日志到数据库
    }


}
